package com.df.springmvc.model.dao;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import org.springframework.stereotype.Repository;
import com.common.bean.SQLInsertBean;
import com.common.bean.SQLResultBean;
import com.common.bean.SQLUpdateBean;
import com.common.util.SN_GUID;
import com.common.util.Date.DateUtil;
import com.df.springmvc.common.bean.MsgBean;
import com.df.springmvc.common.util.Rem;
import com.df.springmvc.common.util.WFUtil;
import com.df.springmvc.workflow.ActicityDao;
import com.google.gson.internal.LinkedTreeMap;

/**
 * 本类只做数据库操作处理
 * @author David
 */
@Repository
public class WorkFlowDao extends ActicityDao{
	@Override
	public Object add(HashMap<String,Object> map) throws Exception{
		// TODO Auto-generated method stub
		Object rs;
		if(true){
			SQLInsertBean bean=new SQLInsertBean("B_Apply_INFO",map);
			rs=excuteSqlBean(bean);
		}
		if(true){
			HashMap<String,Object> procMap=new HashMap<String,Object>();
			procMap.put("applyer",getCurrentUserBean().getUserId());
			Rem.print("开发人员注意先创建业务表数据后，取到guid,在进行关联流程，在流程设计中");
			MsgBean bean=WFUtil.doNew("apply_test_1","" + map.get("guid"),"" + map.get("rootCause"),procMap);
			if(bean.isStatus() == false){
				throw new RuntimeException("流程创建失败");
			}
		}
		return rs;
	}
	@Override
	public Object upd(HashMap<String,Object> map) throws Exception{
		SQLUpdateBean bean=new SQLUpdateBean("B_Apply_INFO",map);
		bean.putCondition("guid",map.get("guid"));
		bean.removeColumn("guid");
		return excuteSqlBean(bean);
	}
	@Override
	public Object del(HashMap<String,Object> map) throws Exception{
		// TODO Auto-generated method stub
		return updateSql("delete B_Apply_INFO where guid  =:guid",map);
	}
	/**
	 * 如果没有数据返回true
	 * @param id
	 * @return
	 * @throws Exception
	 */
	public boolean check(String id) throws Exception{
		// TODO Auto-generated method stub
		String sql="select 1 from B_Apply_INFO where applyId=?";
		SQLResultBean resultBean=querySqlToSQLResultBean(sql,new Object[]{id},0,0);
		return resultBean.getMapList().size() == 0?true:false;
	}
	public ArrayList<Object[]> queryApplyList() throws Exception{
		// TODO Auto-generated method stub
		String sql="select 0,guid,ApplyId,rootCause,applytype,applyer,startTime,endTime,applyStatus,days from B_Apply_INFO where status=1  and ('admin'=? or  createby=? or updateby =?)";
		String u=getCurrentUserBean().getUserId();
		SQLResultBean bean=querySqlToSQLResultBean(sql,new Object[]{u,u,u});
		return bean.getList(Object[].class);
	}
	@Override
	public HashMap<String,Object> view(String guid) throws Exception{
		// TODO Auto-generated method stub
		String sql="select guid, ApplyId,rootCause,applytype,applyer,startTime,endTime,applyStatus,days from B_Apply_INFO  where status=1 and guid=? ";
		System.out.println(guid);
		SQLResultBean bean=querySqlToSQLResultBean(sql,new Object[]{guid});
		if(bean.getMapList().size() > 0){
			return bean.getMapList().get(0);
		}else{
			throw new Exception("数据不存在");
		}
	}
	public Object doSubmit(HashMap<String,String> paramMap) throws Exception{
		// TODO Auto-generated method stub
		// 提交时,要先看看流程是否有关联,如没有关联,说时是用户直接进行提交,没有进行保存,需要先进行保存业务数据,然后进行创建流程,进行提交.
		String id="" + paramMap.get("ApplyId");
		String guid="";
		if(check(id)){
			org.apache.log4j.Logger.getLogger(getClass()).info("记录不存在,重新创建新的记录.");
			HashMap<String,Object> map=new HashMap<String,Object>(paramMap);
			guid=SN_GUID.getUUID();
			map.put("guid",guid);
			map.put("status","1");
			map.put("createby",getCurrentUserBean().getUserId());
			map.put("createtime",new Date());
			map.put("updateby",getCurrentUserBean().getUserId());
			map.put("updatetime",new Date());
			map.put("ApplyId","AP_" + DateUtil.getInstance().setDateFormat("yyyyMMdd_HHmmssSSS"));
			map.put("applyStatus","已提交");
			add(map);
			HashMap<String,Object> procMap=new HashMap<String,Object>();
			procMap.put("applyer",getCurrentUserBean().getUserId());
			Rem.print("开发人员注意先创建业务表数据后，取到guid,在进行关联流程，在流程设计中");
			MsgBean bean=WFUtil.doNew("apply_test_1","" + map.get("guid"),"" + map.get("rootCause"),procMap);
			if(bean.isStatus() == false){
				throw new RuntimeException("流程创建失败");
			}
		}else{
			HashMap<String,Object> map=new HashMap<String,Object>(paramMap);
			map.put("updateby",getCurrentUserBean().getUserId());
			map.put("updatetime",new Date());
			map.put("applyStatus","已提交");
			guid=paramMap.get("guid");
			upd(map);
		}
		org.apache.log4j.Logger.getLogger(getClass()).info("记录存在后,提交流程记录.");
		HashMap<String,Object> completeMap=new HashMap<String,Object>();
		String taskId="";
		ArrayList<HashMap<String,Object>> taskIds=WFUtil.queryTaskIdByGuid(guid);
		for(HashMap<String,Object> map:taskIds){
			taskId="" + map.get("id");
		}
		completeMap.put("approve1","user1");
		completeMap.put("approveGroup1","group1");// 设置流程节点下一审核人
		MsgBean bean=WFUtil.doComplete(taskId,getCurrentUserBean().getUserId(),completeMap);
		if(bean.isStatus() == false){
			throw new RuntimeException("流程提交失败:" + bean.getContent());
		}
		return "流程提交成功";
	}
	/**
	 * 进行初审
	 * @param paramMap
	 * @return
	 */
	public Object doApply1(HashMap<String,String> paramMap){
		// TODO Auto-generated method stub
		HashMap<String,Object> completeMap=new HashMap<String,Object>();
		completeMap.put("approve2","user2");// 设置流程节点下一审核人
		completeMap.put("approveGroup2","group2");// 设置流程节点下一审核人
		completeMap.put("status1","true".equalsIgnoreCase(paramMap.get("status"))?"ok":"");// 设置流程节点处理结果
		completeMap.put("comment1",paramMap.get("comment"));// 设置流程节点的备注
		String taskId=paramMap.get("taskId");
		MsgBean bean=WFUtil.doComplete(taskId,getCurrentUserBean().getUserId(),completeMap);
		if(bean.isStatus() == false){
			throw new RuntimeException("流程提交失败:" + bean.getContent());
		}
		return bean.getContent();
	}
	public Object doApply2(HashMap<String,String> paramMap){
		// TODO Auto-generated method stub
		HashMap<String,Object> completeMap=new HashMap<String,Object>();
		org.apache.log4j.Logger.getLogger(getClass()).info("设置会签人");
		completeMap.put("collection",Arrays.asList("user1","user2","user3"));// 设置会签处理人
		completeMap.put("status2","true".equalsIgnoreCase(paramMap.get("status"))?"ok":"");// 设置流程节点处理结果
		completeMap.put("comment2",paramMap.get("comment"));// 设置流程节点的备注
		String taskId=paramMap.get("taskId");
		MsgBean bean=WFUtil.doComplete(taskId,getCurrentUserBean().getUserId(),completeMap);
		if(bean.isStatus() == false){
			throw new RuntimeException("流程提交失败:" + bean.getContent());
		}
		return bean.getContent();
	}
	public Object doApply3(HashMap<String,String> paramMap){
		// TODO Auto-generated method stub
		HashMap<String,Object> completeMap=new HashMap<String,Object>();
		org.apache.log4j.Logger.getLogger(getClass()).info("设置会签条件");
		// 在流程设计时,对完成条件只用进行设置完成条件的变量.其条件结果放在代码中进行实现.
		// 完成条件默认为false,如果业务需要所有人必需处理.则可以在流程定义设计时,将完成条件设置为false,永远所有人必需处理.
		// 如果节点是多实例的，会在节点底部显示三条短线。 三条竖线表示实例会并行执行。 三条横线表示顺序执行。
		completeMap.put("completionCondition",false);
		// /////////////////////////////////////////
		// 对会签结果进行统计.查询其它人的处理结果
		System.out.println(paramMap);
		String guid=paramMap.get("guid");
		String taskId=paramMap.get("taskId");
		HashMap<String,Object> queryTaskByTaskId=WFUtil.queryTaskByTaskId(taskId);
		// 获取task对应的时间参数
		String startTime="" + queryTaskByTaskId.get("createtime");
		org.apache.log4j.Logger.getLogger(getClass()).info("startTime===" + startTime);
		// 1.查询流程下同一个流程实例下的任务
		ArrayList<HashMap<String,Object>> taskList=WFUtil.queryTaskIdByGuid(guid);
		org.apache.log4j.Logger.getLogger(getClass()).info("taskList 大小:" + taskList.size());
		ArrayList<String> statutsList=new ArrayList<String>();
		for(HashMap<String,Object> map:taskList){
			// org.apache.log4j.Logger.getLogger(getClass()).info("map:" + map);
			if(startTime.equalsIgnoreCase(map.get("startTime") + "") && !taskId.equalsIgnoreCase("" + map.get(""))){
				Object json=map.get("param");
				if(json instanceof LinkedTreeMap){
					LinkedTreeMap t=(LinkedTreeMap)json;
					String status="" + t.get("status");// 获取历史结果
					statutsList.add(status);
				}
			}
		}
		org.apache.log4j.Logger.getLogger(getClass()).info("statutsList==" + statutsList);
		// 如业务现定为:如果有一个不通过.定为这个节点不通过.这个逻辑代码需要开发人员进行编写代码实现
		boolean rsb=true;
		for(String status:statutsList){
			if("false".equalsIgnoreCase(status)){
				rsb=false;
			}
		}
		if("false".equalsIgnoreCase(paramMap.get("status"))){
			rsb=false;
		}
		org.apache.log4j.Logger.getLogger(getClass()).info("最终结果:rsb" + rsb);
		// 2.通过任务Id查询查询处理状态与意见
		// //////////////////
		if(true){
			completeMap.put("status",paramMap.get("status"));// 设置流程节点处理结果
			completeMap.put("status3",rsb?"ok":"");// 设置流程节点处理结果
			completeMap.put("FinancialUser","FinancialUser");// 设置流程节点处理结果
			completeMap.put("PersonnelUser","PersonnelUser");// 设置流程节点处理结果
			completeMap.put("comment",paramMap.get("comment"));// 设置流程节点的备注
			MsgBean bean=WFUtil.doComplete(taskId,getCurrentUserBean().getUserId(),completeMap);
			return bean.getContent();
		}else{
			return "error";
		}
	}
	public Object doPersonnel(HashMap<String,String> paramMap){
		org.apache.log4j.Logger.getLogger(getClass()).info("进行人事登记");
		// TODO Auto-generated method stub
		HashMap<String,Object> completeMap=new HashMap<String,Object>();
		String taskId=paramMap.get("taskId");
		completeMap.put("comment",paramMap.get("comment"));// 设置流程节点的备注
		completeMap.put("ArchiveUser","ArchiveUser");//
		MsgBean bean=WFUtil.doComplete(taskId,getCurrentUserBean().getUserId(),completeMap);
		return bean.getContent();
	}
	public Object doFinancial(HashMap<String,String> paramMap){
		org.apache.log4j.Logger.getLogger(getClass()).info("进行财务登记");
		// TODO Auto-generated method stub
		HashMap<String,Object> completeMap=new HashMap<String,Object>();
		String taskId=paramMap.get("taskId");
		completeMap.put("comment",paramMap.get("comment"));// 设置流程节点的备注
		completeMap.put("ArchiveUser","ArchiveUser");//
		MsgBean bean=WFUtil.doComplete(taskId,getCurrentUserBean().getUserId(),completeMap);
		return bean.getContent();
	}
	public Object doArchive(HashMap<String,String> paramMap){
		// TODO Auto-generated method stub
		org.apache.log4j.Logger.getLogger(getClass()).info("进行归档");
		HashMap<String,Object> completeMap=new HashMap<String,Object>();
		String taskId=paramMap.get("taskId");
		completeMap.put("comment",paramMap.get("comment"));// 设置流程节点的备注
		MsgBean bean=WFUtil.doComplete(taskId,getCurrentUserBean().getUserId(),completeMap);
		return bean.getContent();
	}
}
